package com.doit.day02;

import com.doit.day01.MyTools;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.*;

public class _01_qq音乐播放次数topN {
    public static void main(String[] args) throws InterruptedException {
        //需要造数据
//        ArrayList<String> list = new ArrayList<>();
        String [] arr = {"晴天", "阴天", "发如雪","青花瓷","烟花易冷","稻香","花海","夜曲","双节棍","本草纲目"};
        Jedis jedis = MyTools.getJedis();
        new Thread(new ProducerThread(arr,jedis)).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        //每隔5s就输出一次结果
                        //针对权重分数倒序排列，取前3 //Tuple 元祖
                        Set<Tuple> song = jedis.zrevrangeWithScores("song", 0, 2);
                        for (Tuple tuple : song) {
                            String element = tuple.getElement();
                            double score = tuple.getScore();
                            System.out.println("歌曲是："+element+"==> 次数是："+score);
                        }
                        System.out.println("================================");
                    }
                },10000,5000);

            }
        }).start();



    }
}

class ProducerThread implements Runnable{
    private String [] arr;
    private Jedis jedis;

    public ProducerThread(String [] arr, Jedis jedis){
        this.arr = arr;
        this.jedis = jedis;
    }

    @Override
    public void run() {
        Random random = new Random();
        //让这些歌随机的出来
        while (true){
            int index = random.nextInt(arr.length);
            String song = arr[index];
            //读取数据，来收集统计每首音乐被播放的次数
            //统计的时候就要用到redis中的sorted set 这种结构 用播放次数作为权分数，用音乐名作为元素
            jedis.zincrby("song",1.0,song);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
